package com.lanxin.qx.controller;

import com.lanxin.qx.entity.QxFunction;
import com.lanxin.qx.entity.QxRole;
import com.lanxin.qx.service.IQxFunctionService;
import com.lanxin.qx.service.IQxRoleFunctionService;
import com.lanxin.qx.service.IQxRoleService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/qx/role")  // 与角色管理统一路径前缀
public class QxFunctionController {

    private static final Logger logger = Logger.getLogger(QxFunctionController.class);

    @Autowired
    private IQxRoleService roleService;  // 角色服务

    @Autowired
    private IQxFunctionService functionService;  // 权限服务

    @Autowired
    private IQxRoleFunctionService roleFunctionService;  // 角色-权限关联服务

    //列表权限
    @RequestMapping("/listPermission")
    public String listPermission( @SessionAttribute("empOid")Integer oid,
                                  Model model) {
        List<QxFunction> listFunction = functionService.listQxFunction(oid);
        model.addAttribute("listFunction", listFunction);
        return "qx/listMyFun";
    }

    /**
     * 跳转设置角色权限页面
     */
    @RequestMapping("/toEditRoleFun")
    public String toEditRoleFun(@RequestParam Integer oid, Model model) {
        // 1.查询角色信息（用于页面显示角色名称）
        QxRole role = roleService.getById(oid);
        if (role == null) {
            model.addAttribute("error", "角色不存在！");
            return "home";
        }
        model.addAttribute("role", role);

        // 2.查询所有权限
        Map<QxFunction, List<QxFunction>> functionMap = functionService.getFunctionsGroupByParent();
        model.addAttribute("functionMap", functionMap);

        // 3.查询该角色已拥有的权限ID列表
        List<Integer> checkedFuncIds = functionService.getFunctionIdsByRoleId(oid);
        model.addAttribute("checkedFuncIds", checkedFuncIds);

        return "qx/EditRoleFun";
    }

    /**
     * 保存设置角色权限
     */
    @RequestMapping("/editRoleFun")
    public String editRoleFun(
            @RequestParam Integer oid,
            @RequestParam(required = false) String fids,
            Model model) {
        try {
            // 1.处理权限ID列表（字符串转List<Integer>）
            List<Integer> functionIds = new ArrayList<>();
            if (fids != null && !fids.trim().isEmpty()) {
                functionIds = Arrays.stream(fids.split(","))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
            }

            // 2.保存角色权限关联
            boolean success = roleFunctionService.saveRolePermissions(oid, functionIds);

            // 3.添加操作结果提示
            if (success) {
                model.addAttribute("msg", "权限配置保存成功！");
            } else {
                model.addAttribute("msg", "权限配置保存失败，请重试！");
            }
        } catch (Exception e) {
            logger.error("保存角色权限失败", e);
            model.addAttribute("msg", "服务器错误：" + e.getMessage());
        }

        // 4.重定向回权限编辑页面（带角色ID）
        return "redirect:/qx/role/listPermission?oid=" + oid;
    }
}